<?php

require_once 'Mage/Customer/controllers/AccountController.php';
class Webkul_Marketplacepartner_PartnerproductsController extends Mage_Customer_AccountController
{
	public function indexAction(){
		$this->loadLayout( array('default','customer_account_products'));
        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
		$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('Customer Products'));
    	$this->renderLayout();
	}
	public function myproductslistAction(){
		$this->loadLayout( array('default','marketplace_account_productlist'));
        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
		$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('My Product List'));
    	$this->renderLayout();
	}
	public function mydashboardAction(){
		$this->loadLayout( array('default','marketplace_account_dashboard'));
        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
		$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('My Dashboard'));
    	$this->renderLayout();
	}
	public function myorderhistoryAction(){
		$this->loadLayout( array('default','marketplace_account_orderhistory'));
        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
		$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('My Order History'));
    	$this->renderLayout();
	}
	public function simpleproductAction() {
		if($this->getRequest()->isPost()){
			list($data, $errors) = $this->validatePost();
			$wholedata=$this->getRequest()->getParams();
			if(empty($errors)){		
				Mage::getModel('marketplacepartner/sellerpayment')->saveSimpleNewProduct($wholedata);
				$customer = Mage::getModel('customer/customer')->load($wholedata['userid']);
				$cfname=$customer->getFirstname()." ".$customer->getLastname();
				$cmail=$customer->getEmail();
				$catagory_model = Mage::getModel('catalog/category');
				$categoriesy = $catagory_model->load($wholedata['category']);
				$categoryname=$categoriesy->getName();
				$emailTemp = Mage::getModel('core/email_template')->loadDefault('approveproduct');
				$emailTempVariables = array();
				$write = Mage::getSingleton('core/resource')->getConnection('core_write');
				// mysql prefix checking and execute code
				$readresult=$write->query("select role_id from ".Mage::getConfig()->getTablePrefix()."admin_role  where role_name = 'Administrators'");
				$row = $readresult->fetch();
				// mysql prefix checking and execute code
				$sql= 'select user_id from '.Mage::getConfig()->getTablePrefix().'admin_role where parent_id  = "'.$row['role_id'].'" ';
				foreach($write->fetchAll($sql) as $adm){
					// mysql prefix checking and execute code
					$readresultadmin=$write->query("select * from  ".Mage::getConfig()->getTablePrefix()."admin_user  where user_id = '".$adm['user_id']."'");
					$rowadmin = $readresultadmin->fetch();
					$emailTempVariables['myvar1'] = $wholedata['name'];
					$emailTempVariables['myvar2'] =$categoryname;
					$emailTempVariables['myvar3'] =$rowadmin['firstname']." ".$rowadmin['lastname'];$processedTemplate = $emailTemp->getProcessedTemplate($emailTempVariables);
					$emailTemp->setSenderName($cfname);
					$emailTemp->setSenderEmail($cmail);
					$emailTemp->send($rowadmin['email'],$rowadmin['firstname']." ".$rowadmin['lastname'],$emailTempVariables);
					}
			}else{
				foreach ($errors as $message) {$this->_getSession()->addError($message);}
				$_SESSION['new_products_errors'] = $data;
			}
			if (empty($errors))
				$this->_getSession()->addSuccess(Mage::helper('marketplacepartner')->__('Your product was successfully Saved'));
				$this->_redirect('marketplacepartner/partnerproducts/simpleproduct/');
		}
		else{
			$this->loadLayout( array('default','marketplace_account_simpleproduct'));
			$this->_initLayoutMessages('customer/session');
			$this->_initLayoutMessages('catalog/session');
			$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('MarketPlace Product Type: Simple Product'));
			$this->renderLayout();
		}
	}
	
	public function editsimpleAction() {
	die();
		if($this->getRequest()->isPost()){
			$id = $this->getRequest()->getParam('productid');
			if($id !== false){
				list($data, $errors) = $this->validatePost();
				if(!empty($errors)){
					foreach($errors as $message){$this->_getSession()->addError($message);}
					$this->_redirect('customer/products/edit/', array('id' => $id));
				}else{
					$customerId = $this->_getSession()->getCustomer()->getid();
					$error = Mage::getModel('marketplacepartner/productsales')->getSimplePostAction($this->getRequest(),$customerId,$id);
					
					if(empty($error)){$this->_getSession()->addSuccess(Mage::helper('marketplacepartner')->__('Your product was successfully updated'));}else{
						$this->_getSession()->addError(Mage::helper('marketplacepartner')->__('Product info was saved but was imposible to save the image'));
						foreach ($error as $message){$this->_getSession()->addError($message);}
					}
					$this->_redirect('marketplacepartner/partnerproducts/myproductslist/');
				}
			}
		}
		else
		{		
			$this->loadLayout( array('default','marketplace_account_simpleproductedit'));
			$this->_initLayoutMessages('customer/session');
			$this->_initLayoutMessages('catalog/session');
			$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('MarketPlace: Edit Simple Product'));
			$this->renderLayout();
		}
	}
	
	public function askquestionAction(){
		$email = Mage::getModel('customer/customer')->load($_POST['seller-id'])->getEmail();
			$admin = Mage::getModel('admin/user')->load(1)->getEmail();
			$headers = 'From: '.$email."\r\n" .
		   'Reply-To: '.$email. "\r\n" .
		   'X-Mailer: PHP/' . phpversion();
			mail($admin,$_POST['subject'],$_POST['ask'],$headers);
	}
	
	public function deletecustomAction()
	{
		$id= $this->getRequest()->getParams('id');
		require_once 'app/Mage.php';
		Mage::init();
		$set=Mage::getModel('catalog/product_option')->load($id['id'])->delete();
		return 0;
	} 
	public function editapprovedsimpleAction() {
		if($this->getRequest()->isPost()){
			$id= $this->getRequest()->getParam('productid');
			Mage::getModel('marketplacepartner/sellerpayment')->editApprovedProduct($this->getRequest(),$id,$this->getRequest()->getParams());
			$this->_redirect('marketplacepartner/partnerproducts/myproductslist/');
			$this->_getSession()->addSuccess($this->__('Your Product Is Been Sucessfully Updated'));
		}
		else{
			$this->loadLayout( array('default','marketplace_account_simpleapprovedproductedit'));
			$this->_initLayoutMessages('customer/session');
			$this->_initLayoutMessages('catalog/session');
			$this->getLayout()->getBlock('head')->setTitle( Mage::helper('marketplacepartner')->__('MarketPlace: Edit Simple Magento Product'));
			$this->renderLayout();
		}
	}
	public function newfeedbackAction(){
		$wholedata=$this->getRequest()->getPost();
		Mage::getModel('marketplacepartner/feedback')->saveFeedbackdetail($wholedata);
		$this->_redirect("marketplacepartner/feedback?id=".$wholedata['proownerid'].'&result=success');
		$this->_getSession()->addSuccess( Mage::helper('marketplacepartner')->__('Your Review was successfully saved'));
		
	}
	public function deleteAction(){
		$urlapp=$_SERVER['REQUEST_URI'];
		$record=Mage::getModel('marketplacepartner/sellerpayment')->deleteProduct($urlapp);
		$this->_redirect('marketplacepartner/partnerproducts/myproductslist/');
		$this->_getSession()->addSuccess( Mage::helper('marketplacepartner')->__('Your Product Has Been Sucessfully Deleted From Your Account'));
	}
	public function deleteapprovedAction(){
		$urlapp=$_SERVER['REQUEST_URI'];
		$record=Mage::getModel('marketplacepartner/marketplacepartner')->deleteApprovedProduct($urlapp);	
		$this->_redirect('marketplacepartner/partnerproducts/myproductslist/');				
		$this->_getSession()->addSuccess( Mage::helper('marketplacepartner')->__('Your Product Has Been Sucessfully Deleted From Magento AS Well From Your Account'));
	}
	
	public function deleteimageAction(){
		$data= $this->getRequest()->getParams();
		$_product = Mage::getModel('catalog/product')->load($data['pid'])->getMediaGalleryImages();
		$main = explode('/',$data['file']);	
		foreach($_product as $_image) { 
			$arr = explode('/',$_image['path']);
			if(array_pop($arr) != array_pop($main)){
				$newimage = $_image['path'];
				$id = $_image['value_id'];
				break;
			}		
		}
		$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
		$mediaApi->remove($data['pid'], $data['file']);
		$mediaApi->remove($data['pid'],$id);
		$mediaApi->save();
		$objprod = Mage::getModel('catalog/product')->load($data['pid']);
		$objprod->addImageToMediaGallery( $newimage, array ('image','small_image','thumbnail'), true, false);
		$objprod->save();
		$mediaApi->remove($data['pid'],$id);
	}
	
	
	private function validatePost(){
		$errors = array();
		$data = array();
		foreach( $this->getRequest()->getParams() as $code => $value){
			switch ($code) :
				case 'name':
					if(trim($value) == '' ){$errors[] = Mage::helper('marketplacepartner')->__('Name has to be completed');} 
					else{$data[$code] = $value;}
					break;
				case 'description':
					if(trim($value) == '' ){$errors[] = Mage::helper('marketplacepartner')->__('Description has to be completed');} 
					else{$data[$code] = $value;}
					break;
				case 'short_description':
					if(trim($value) == ''){$errors[] = Mage::helper('marketplacepartner')->__('Short description has to be completed');} 
					else{$data[$code] = $value;}
					break;
				case 'price':
					if(!preg_match("/^([0-9])+?[0-9.]*$/",$value)){$errors[] = Mage::helper('marketplacepartner')->__('Price should contain only decimal numbers');}else{$data[$code] = $value;}
				case 'weight':
					if(!preg_match("/^([0-9])+?[0-9.]*$/",$value)){
						$errors[] = Mage::helper('marketplacepartner')->__('Weight should contain only decimal numbers');
					}else{$data[$code] = $value;}
					break;
				case 'stock':
					if(!preg_match("/^([0-9])+$/",$value)){
						$errors[] = Mage::helper('marketplacepartner')->__('Product stock should contain only an integer number');
					}else{$data[$code] = $value;}
					break;
			endswitch;
		}
		return array($data, $errors);
	}
	
	//for check sku
	public function verifyskuAction(){
		$sku=$this->getRequest()->getParam('sku');
		$id = Mage::getModel('catalog/product')->getIdBySku($sku);
		if ($id){
			$avl=0;//$sku . "exists";
		}
		else{
			$avl=1; //$msg=$sku . "does not exist";
		} 
		
		 echo json_encode(array("avl"=>$avl));
	}
	
	/*private function uploadZipSample($image, $customer_partner_product_id){
		$max_size = 3670016; // the max. size for uploading
		$my_upload = Mage::getModel('marketplaceprofile/uploadzipsample');
		if (!is_dir(Mage::getBaseDir().'/media/customersproducts/')){
			mkdir(Mage::getBaseDir().'/media/customersproducts/', 0755);
		}
		// "files" is the folder for the uploaded files
		$my_upload->upload_dir = Mage::getBaseDir().'/media/customersproducts/'.$customer_partner_product_id."/"; 
		$my_upload->extensions = array(".gif", ".jpg", ".jpeg",".png"); // specify the allowed extensions here
		$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
		$my_upload->the_temp_file = $image['tmp_name'];
		$my_upload->the_file = $image['name'];
		$my_upload->http_error = $image['error'];
		$my_upload->replace = true;  // because only a checked checkboxes is true
		// use this boolean to check for a valid filename
		$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "y"; 
		$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
		// new name is an additional filename information, use this to rename the uploaded file
		if($my_upload->upload($new_name)){return true;} 
		else {return $my_upload->show_error_string();}
	}
	
	
	private function uploadZip($image, $customer_partner_product_id){
		$max_size = "1113670016000"; // the max. size for uploading
		$my_upload = Mage::getModel('marketplaceprofile/uploadzip');
		if(!is_dir(Mage::getBaseDir().'/media/customersproducts/')){
			mkdir(Mage::getBaseDir().'/media/customersproducts/', 0755);
		}
		// "files" is the folder for the uploaded files
		$my_upload->upload_dir = Mage::getBaseDir().'/media/customersproducts/'.$customer_partner_product_id."/"; 
		$my_upload->extensions = array(".zip", ".ap", ".psd",".rar",".pdf"); // specify the allowed extensions here		
		$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
		$my_upload->the_temp_file = $image['tmp_name'];
		$my_upload->the_file = $image['name'];
		$my_upload->http_error = $image['error'];
		$my_upload->replace = true;  // because only a checked checkboxes is true
		// use this boolean to check for a valid filename
		$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "y"; 
		$new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
		// new name is an additional filename information, use this to rename the uploaded file
		if($my_upload->upload($new_name)) {return true;} 
		else {return $my_upload->show_error_string();}
	}*/
	
	
	
}
